<?php

namespace App\Service\Wechat;

use App\Service\WeChat;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * App\Service\Wechat\MaterialNews
 *
 * @mixin \Eloquent
 */
class MaterialNews extends Model implements MaterialInterFace
{
    //
    protected $table = 'wx_materail_news';
    private $wechatManager;

    public function __construct (array $attributes = [],WeChat $wechat)
    {
        parent::__construct($attributes);
        $this->wechatManager = $wechat;
    }


    public function sync ()
    {
        // TODO: Implement sync() method.
        //step1.Getting lists from  `wechat`;
        $res = $this->wechatManager->getMaterial(Material::NEWS);
        $lists = $res['item'];
        //step2.clear the table
        DB::table($this->table)->truncate();
        //setp3.fill the data into the table
        $insertData = [];
        foreach ($lists as $list){
            $insertData[] = [
                'media_id'  =>  $list['media_id'],
                'update_time'   =>  $list['update_time']
            ];
        }
        if($insertData) {
            DB::table($this->table)->insert($insertData);
        }
    }

    public  static function upload ($data)
    {
        // TODO: Implement upload() method.
        if($data&&$data->media_id){
            $model = new MaterialImage();
            $model->media_id = $data->media_id;
            $model->save();
        }
    }

    public static function getAll ()
    {
        // TODO: Implement getAll() method.
        $list = self::all();
        return $list?$list->toArray():[];
    }

    public static function getByMediaId ()
    {
        // TODO: Implement getByMediaId() method.
    }
}
